<template>
  <div style="display: flex; flex-direction: column; align-items: center;">
    <div style="display: flex; flex-wrap: wrap; justify-content: center; margin-bottom: 20px">
      <div class=roomwrap v-for="(value, key) in bedMap" :key="key">
        <RoomBedSelect :title="key" :bedList="value" :curBed="curSel" :curUser='curUser' @event-haveseat="haveSeat" @event-leaveseat="leaveSeat" @event-setcurseat="setCurSeat"/>
      </div>
      <el-empty v-if="isEmptyOpeningBed" description="工位没有开放"/>
    </div>
    <div>
      <el-button @click="confirmCurSel">确认</el-button>
      <el-button @click="resetPage">重置</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import {RoomBedSelect} from "@/components/RoomBedSelect"
import { RoomApi, RoomVO } from '@/api/ecg/room'
import {useUserStore} from "@/store/modules/user";
import {ElMessage, ElMessageBox} from "element-plus";
import {cloneDeep} from "lodash-es";
import {DoctorApi} from "@/api/ecg/doctor";
import {useRoomStore} from "@/store/modules/room";
const {  push } = useRouter()

defineOptions({ name: 'RoomLoginSelect' })

const route = useRoute();

const userStore = useUserStore()
const roomStore = useRoomStore()
const curUser = userStore.getUser

const isEmptyOpeningBed = ref<boolean>(true);
const bedMap = ref() // 列表的数据
const curSel = ref<RoomVO>({
  id: null,
  roomId: null,
  roomName: null,
  bedNo: null,
  status: null,
  docId: null,
  docName: null,
  ip: "",
  checkTypes: [],
  opType: 0
})

/** 初始化 **/
onMounted(() => {
  console.info( curUser.id + " onMounted")
    getList()
})

onActivated(() => {
  console.info( curUser.id + " onActivated")
    getList()
})

const resetPage = () => {
    getList()
}

/** 查询列表 */
const getList = async () => {
  resetCurSel()

  console.info("getList before")
  const data = await RoomApi.getOpeningBedMap()
  bedMap.value = data;
  console.info("getList after " + data)

  isEmptyOpeningBed.value = true
  for (const key in data) {
    isEmptyOpeningBed.value = false

    if (roomStore.getIsSetRoom) {
      const roomVOArray = data[key] as RoomVO[];
      roomVOArray.forEach((roomVO) => {
        if (roomVO.docId === curUser.id
            && roomVO.roomId === roomStore.room!.roomId
            && roomVO.bedNo === roomStore.room!.bedNo) {
          curSel.value = roomVO
          roomStore.setRoomInfoAction(curSel.value)
        }
      })
    }
  }
}

const confirmCurSel = () => {
  if (curSel.value.docId === null ) {
    ElMessage({
      message: '请先选择工作的位置!',
      type: 'info',
      duration: 3000 // 自动关闭时间，默认为3000ms
    });
    return
  }

  // curSel.value.opType 0 1 2
  if (curSel.value.opType === 0) {
    push({path: "/ecg/doc/routine"})
  }
  else if (curSel.value.opType === 1) {
    push({path: "/ecg/doc/dev-ready"})
  }
  else if (curSel.value.opType === 2) {
    push({path: "/ecg/doc/dev-install"})
  }
  else {
    push({path: route.redirectedFrom?.fullPath})
  }

/*
  if (isStringEmpty(route.redirectedFrom?.fullPath))
    push({ path: "/ecg/doc/dev-ready"})
  else if(route.redirectedFrom?.fullPath === "/roomselect" )
    push({ path: "/ecg/doc/dev-ready"})
  else if(route.redirectedFrom?.fullPath === "/ecg/roomselect" )
    push({ path: "/ecg/doc/dev-ready"})
  else
    push({ path: route.redirectedFrom?.fullPath})
*/
}

const haveSeatConfirm = async (newRoomVO: RoomVO) => {
  if (newRoomVO !== curSel.value) {
    let data;
/*  保留这块逻辑
    if (curSel.value.docId !== null) {
      data = await DoctorApi.bedDoctorOff(curSel.value)
      if (data !== 0) {
        ElMessage({
          message: '内部错误!' + data,
          type: 'info',
          duration: 3000 // 自动关闭时间，默认为3000ms
        });
        return
      }
    }
*/

    resetCurSel()
    await roomStore.clearRoomInfoAction()

    const tempRoomVO = cloneDeep(newRoomVO)
    tempRoomVO.docId = curUser.id
    tempRoomVO.docName = curUser.nickname
    data = await DoctorApi.bedDoctorOn(tempRoomVO)
    if (data !== 0) {
      ElMessage({
        message: '内部错误!' + data,
        type: 'info',
        duration: 3000 // 自动关闭时间，默认为3000ms
      });
      return
    }

    await roomStore.setRoomInfoAction(tempRoomVO)
    newRoomVO.docId = curUser.id
    newRoomVO.docName = curUser.nickname
    curSel.value = newRoomVO;
  }

  // curSel.value.opType 0 1 2
  if (newRoomVO.opType === 0) {
    push({path: "/ecg/doc/routine"})
  }
  else if (newRoomVO.opType === 1) {
    push({path: "/ecg/doc/dev-ready"})
  }
  else if (newRoomVO.opType === 2) {
    push({path: "/ecg/doc/dev-install"})
  }
  else {
    push({path: route.redirectedFrom?.fullPath})
  }

/*
  // curSel.value.opType 0 1 2
  if (isStringEmpty(route.redirectedFrom?.fullPath)) {
    push({path: "/ecg/doc/dev-ready"})
  }
  else if(route.redirectedFrom?.fullPath === "/roomselect" ) {
    push({path: "/ecg/doc/dev-ready"})
  }
  else if(route.redirectedFrom?.fullPath === "/ecg/roomselect" ) {
    push({path: "/ecg/doc/dev-ready"})
  }
  else {
    push({path: route.redirectedFrom?.fullPath})
  }
*/
}

const leaveSeatConfirm = async (roomVO: RoomVO) => {
  if (roomVO.docId !== null) {
      let data = await DoctorApi.bedDoctorOff(roomVO)
      if (data !== 0) {
          ElMessage({
              message: '内部错误!' + data,
              type: 'info',
              duration: 3000 // 自动关闭时间，默认为3000ms
          });
          return
      }
  }

  resetCurSel()
  await roomStore.clearRoomInfoAction()
  getList()
}

const haveSeat = async (newRoomVO: RoomVO) => {
  ElMessageBox.confirm(
      '入座, 是否继续?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    haveSeatConfirm(newRoomVO)
  }).catch(() => {
  });
}

const leaveSeat = (roomVO: RoomVO) => {
  ElMessageBox.confirm(
      '离座, 是否继续?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    leaveSeatConfirm(roomVO)
  }).catch(() => {
  });
}

// 同时坐了多个工位时，设定当前会话的工位
const setCurSeat = (roomVO: RoomVO) => {
  roomStore.setRoomInfoAction( roomVO )
  curSel.value = roomVO

  // curSel.value.opType 0 1 2
  if (roomVO.opType === 0) {
    push({path: "/ecg/doc/routine"})
  }
  else if (roomVO.opType === 1) {
    push({path: "/ecg/doc/dev-ready"})
  }
  else if (roomVO.opType === 2) {
    push({path: "/ecg/doc/dev-install"})
  }
  else {
    push({path: route.redirectedFrom?.fullPath})
  }
}

const resetCurSel = () => {
    curSel.value.id = null
    curSel.value.roomId = null
    curSel.value.roomName = null
    curSel.value.bedNo = null
    curSel.value.status = null
    curSel.value.docId = null
    curSel.value.docName = null
}

</script>

<style scoped lang="scss">
.roomwrap {
  margin-right: 20px;
}
</style>
